package com.code.coinprice.managers;

import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import javax.annotation.Resource;
import java.net.URI;

@Component
public class HttpManager {

    @Resource
    private RestTemplate restTemplate;

    public ResponseEntity<Object> sendGetRequest(String url, String apiKey, String apiValue, MultiValueMap<String, String> params) {
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.ACCEPT_ENCODING, "gzip,deflate");
        if (!StringUtils.isEmpty(apiKey) && !StringUtils.isEmpty(apiValue)) {
            headers.add(apiKey, apiValue);
        }
        getJsonHeader(headers);
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        URI uri = builder.queryParams(params).build().encode().toUri();
        return restTemplate.getForEntity(uri, Object.class);
    }

    /**
     * 构造http请求的头部信息
     */
    private void getJsonHeader(HttpHeaders headers) {
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON.toString());
    }


}
